<%--
  Created by IntelliJ IDEA.
  User: HY
  Date: 2020/9/16
  Time: 20:00
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <c:import url="../template/_header.jsp"/>
    <title>编辑资源-知了[团队知识管理应用]</title>

    <%--tinymce--%>
    <script src="../assets/vendor/tinymce/tinymce.min.js"></script>
    <script src="../assets/vendor/tinymce/langs/zh_CN.js"></script>
</head>

<body>
<div class="re-main">
    <c:import url="../template/_navbar.jsp"/>
    <div class="re-box-6 re-grey mt-85">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-lg-12 col-xl-12">
                    <div class="re-box-decorated">
                        <div class="re-box-content">
                            <%---------------------- 标题 ----------------------%>
                            <div class="re-form-group">
                                <span class="mnt-7 font-2"><strong>&nbsp;标&nbsp;题&nbsp;</strong></span>
                                <input type="text" value="${resource.title}" class="form-control form-control-style-2"
                                       id="title" placeholder="请输入资源标题，内容不可为空">
                            </div>
                            <br/>
                            <%---------------------- 群组 ----------------------%>
                            <div class="re-form-group">
                                <span class="mnt-7 font-2"><strong>&nbsp;群&nbsp;组&nbsp;</strong></span>
                                <div class="group-item">
                                    <c:forEach var="groupList" items="${groupInfoList}">
                                        <button id="group${groupList.id}" class="re-btn re-btn-unselected"
                                                onclick="groupButton(${groupList.id})">${groupList.groupName}</button>
                                    </c:forEach>
                                </div>
                            </div>
                            <br/>
                            <%---------------------- 模板 ----------------------%>
                            <div class="re-form-group" style="line-height:31px;">
                                <span class="mnt-7 font-2"><strong>&nbsp;模&nbsp;板&nbsp;</strong></span>
                                <div class="group-item">
                                    <c:forEach var="templateList" items="${templateInfoList}">
                                        <button id="template${templateList.id}" class="re-btn re-btn-unselected"
                                                onclick="templateButton(${templateList.id})">${templateList.templateName}</button>
                                    </c:forEach>
                                </div>
                            </div>
                            <br/>
                            <%---------------------- 正文编辑 ----------------------%>
                            <div>
                                <div id="editor" autofocus></div>
                            </div>
                            <%---------------------- 书籍目录 ----------------------%>
                            <div class="re-form-group">
                                <textarea class="form-control re-hide book-contents-input" id="contents"
                                          rows="3" placeholder="请按规定格式编辑书籍目录">${resource.contents}</textarea>
                            </div>
                            <br/>
                            <%---------------------- 标签 ----------------------%>
                            <div class="re-form-group">
                                <span class="mnt-7 font-2"><strong>&nbsp;标&nbsp;签&nbsp;</strong></span>
                                <div class="group-item" id="labels">
                                </div>
                            </div>
                            <br/>
                            <%---------------------- 附件 ----------------------%>
                            <div class="re-form-group">
                                <div style="line-height:62px;position:relative;">
                                    <span class="mnt-7 font-2"><strong>&nbsp;附&nbsp;件&nbsp;</strong></span>
                                </div>
                                <input style="display: none" type="file" class="form-control form-control-style-2"
                                       id="attachment" onchange="fileBtnResult()">
                                <div class="font-text-darkgray attach-box" id="drop-zone" onclick="fileBtn()">
                                    <div>拖拽到框中上传附件或点击选取文件</div>
                                </div>
                                <div id="file-list" style="line-height:38px;margin-top: 15px;">
                                </div>
                                <div id="progress-bar" style="line-height:38px;">
                                </div>
                            </div>
                            <br/>
                            <%---------------------- 保存 ----------------------%>
                            <div class="re-form-group" style="float:right">
                                <button class="re-btn" type="submit" id="save" onclick="submit()"><a class="mnt-7">保&nbsp;存</a></button>
                            </div>
                            <br/>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- START: Footer -->
    <c:import url="../template/_footer.jsp"/>
    <!-- END: Footer -->
</div>
</body>

<!-- START: Scripts -->
<c:import url="../template/_include_js.jsp"/>

<%-- tinymce --%>
<script src="../assets/vendor/tinymce/tinymce.min.js"></script>
<script language="JavaScript">

    /* 加载动画 */
    loading("show");

    /* 富文本编辑器 */
    tinymce.init({
        selector: '#editor',
        contextmenu: "bold copy | link | image | imagetools | table | spellchecker",//上下文菜单
        auto_focus: true,
        menubar: false,
        language: 'zh_CN',
        // force_br_newlines: true,
        // force_p_newlines: false,
        // forced_root_block: "",
        // preformatted: true,
        toolbar_mode: 'sliding',
        branding: false,
        content_style: "img {height:auto;max-width:100%;max-height:100%;}",
        plugins: [
            'powerpaste', // plugins中，用powerpaste替换原来的paste
            'image',
            "autoresize",
            "code",
            "link",
            "charmap",
            "emoticons",
            "table",
            "wordcount",
            "advlist",
            "lists",
            "indent2em",
            "hr",
            "toolbarsticky",
            "textpattern"
            //...
        ],
        min_height: 400, //编辑区域的最小高度
        fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt 48pt",
        font_formats: "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
        powerpaste_word_import: 'propmt',// 参数可以是propmt, merge, clear，效果自行切换对比
        powerpaste_html_import: 'propmt',// propmt, merge, clear
        powerpaste_allow_local_images: true,
        paste_data_images: true,
        images_upload_handler: function (blobInfo, success, failure) {
            var xhr, formData;
            xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open("POST", "${pageContext.request.contextPath}/util/uploadImage");
            formData = new FormData();
            formData.append("file", blobInfo.blob(), blobInfo.filename());
            xhr.onload = function (e) {
                var json;
                if (xhr.status != 200) {
                    failure('HTTP Error: ' + xhr.status);
                    return;
                }
                json = JSON.parse(this.responseText);

                if (!json || typeof json.location != 'string') {
                    failure('Invalid JSON: ' + xhr.responseText);
                    return;
                }
                success(json.location);
            };
            xhr.send(formData);
        },
        toolbar: [
            'code insertfile undo redo emoticons | formatselect | forecolor backcolor charmap bold italic underline strikethrough hr | fontselect | fontsizeselect | blockquote subscript superscript removeformat |',
            'bullist numlist | alignleft aligncenter alignright alignjustify outdent indent indent2em | link image table'
        ],
        init_instance_callback: function (editor) {
            <%--console.log("${resource.text}");--%>
            editor.setContent("${fn:replace((fn:replace(resource.text,'\\"','"')), '"', '\\"')}");
            loading("reset");
        },
        my_toolbar_sticky: true,
        toolbar_sticky_always: true,
        toolbar_sticky_elem: "nav",
        toolbar_sticky_elem_autohide: false
    });

    /* 群组标签数据 */
    var groupIds = "${resource.groupId}";
    var labelIds = "${resource.labelId}";
    //加这两个判断是为了后面记录groupIds、labelIds变化时不出问题
    if (groupIds.length != 0) {
        groupIds = ',' + groupIds
    }
    if (labelIds.length != 0) {
        labelIds = ',' + labelIds
    }
    console.log("groupIds:" + groupIds)
    console.log("labelIds:" + labelIds)

    // *************** 显示附件 ***************
    attachment = ${attachment};
    attaLength = attachment.length;
    $(document).ready(function () {
        // console.log(attachment)
        if (attaLength > 0) {
            var htmlStr = $("#file-list").html();
            for (var i = 0; i < attachment.length; i++) {
                htmlStr += "<div id=\"atta" + attachment[i].id + "\" class=\"mnt-7 font-text\"><a>&nbsp;" + attachment[i].name + "&nbsp;</a>&nbsp;&nbsp;<a href=\"javascript:void(0)\" onclick=\"deleteAttachment(attachment," + attachment[i].id + ")\">[删除]</a></div>";
            }
            $("#file-list").html(htmlStr);
        }
    })

    // *************** 上传附件 BEGIN ***************
    //"附件"字段json封装
    function attachmentNewJson(attachmentnew, name, url, attaI) {
        var con = {};
        con["id"] = attaI;
        con["name"] = name;
        con["url"] = url;
        attachment[attachmentnew.length] = con;
        return attachment;
    }
    //删除附件
    function deleteAttachment(attachment, i) {
        var saveUrl = attachment[attachment.findIndex(e => e.id === i)].url
        // console.log(saveUrl);
        $.ajax({
            type: "post",
            url: "${pageContext.request.contextPath}/util/deleteAttachment",
            data: {
                saveUrl: saveUrl
            },
            success: function (data) {
                if (data["result"] == "SUCCESS") {
                    attachment.splice(attachment.findIndex(e => e.id === i), 1)
                    $("#atta" + i).remove();
                    $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '删除成功！'});
                } else {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '删除失败！'});
                }
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '删除失败！'});
            }
        })
        return attachment;
    }
    //”上传附件“按钮
    function fileBtn() {
        document.getElementById('attachment').click();
    }
    var attaName = "";
    //”上传附件“按钮返回值
    function fileBtnResult() {
        //定义表单变量
        var file = document.getElementById('attachment').files;
        if(file.length==0){	//没有文件返回false
            return false
        }
        console.log(file.length);
        //新建一个FormData对象
        var formData = new FormData();
        // //追加文件数据
        // for(i=0;i<file.length;i++){
        //     formData.append("file", file[i]);
        // }
        // console.log(formData);
        formData.append("file", file[0]);
        attaName = file[0].name;
        // 上传
        uploadattachment(formData, attaName)
    }
    //拖拽上传
    var dropZone = document.getElementById('drop-zone');
    //文件拖入框
    dropZone.ondragover = function (e){
        e.preventDefault();  //阻止浏览器默认事件
        e.target.style.border="3px dashed black";
    }
    //文件移除框
    dropZone.ondragleave = function (e){
        e.preventDefault();  //阻止浏览器默认事件
        e.target.style.border="1px dashed darkgray";
    }
    //鼠标松开文件
    dropZone.ondrop = function (e){
        e.preventDefault();  //阻止浏览器默认事件
        e.target.style.border="1px dashed darkgray";
        var file = e.dataTransfer.files
        if(file.length==0){	//没有文件返回false
            return false
        }
        for(i=0; i<file.length; i++){
            //新建一个FormData对象
            var formData = new FormData();
            // //追加文件数据
            // for(i=0;i<file.length;i++){
            //     formData.append("file", file[i]);
            // }
            // console.log(formData);
            formData.append("file", file[i]);
            attaName = file[i].name;
            // 上传
            uploadattachment(formData, attaName)
        }
    }
    //上传附件
    attachmentNew = [];
    attaNewLength = attachmentNew.length;
    function uploadattachment(formData, attaName) {
        console.log(attaName)
        var attaI = attaNewLength + attaLength;//确定新上传文件的“id”
        var xhr = new XMLHttpRequest();//第一步
        xhr.open("POST", "${pageContext.request.contextPath}/util/uploadAttachment");
        xhr.onload = function (e) {
            var json;
            var htmlStr = $("#file-list").html();
            var htmlProgress = "";
            if (xhr.status != 200) {
                alert(xhr.status);
                // failure('HTTP Error: ' + xhr.status);
                return;
            }
            json = JSON.parse(this.responseText);

            if (!json || typeof json.location != 'string') {
                alert(xhr.responseText);
                // failure('Invalid JSON: ' + xhr.responseText);
                return;
            }
            attachmentNew = attachmentNewJson(attachmentNew, attaName, json.location, attaI)
            htmlStr += "<div id=\"atta" + attaI + "\" class=\"mnt-7 font-text\"><a>&nbsp;" + attaName + "&nbsp;</a>&nbsp;&nbsp;<a href=\"javascript:void(0)\" onclick=\"deleteAttachment(attachmentNew," + attaI + ")\">[删除]</a></div>";
            attaI = attaI + 1;
            $("#file-list").html(htmlStr);
            $("#progress-bar").html(htmlProgress);
            $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '上传附件成功'});
            // alert("sc"+json.location+file[0].name);
            // success(json.location);
        };
        xhr.upload.onprogress = function (evt) {
            //侦查附件上传情况
            //通过事件对象侦查
            //该匿名函数表达式大概0.1秒执行一次
            var loaded = evt.loaded;//已经上传大小情况
            var tot = evt.total;//附件总大小
            var per = Math.floor(100 * loaded / tot);  //已经上传的百分比
            var htmlProgress = "<a>&nbsp;" + attaName + "&nbsp;&nbsp;&nbsp;</a><progress value=" + per + " max=\"100\"></progress>"
            $("#progress-bar").html(htmlProgress);
            console.log("已上传：" + per + "%")
        };
        xhr.send(formData);
    }
    // *************** 上传附件 END ***************

    /* 目录输入框高度自适应 */
    function setTextareaHeight() {
        console.log('set textarea height');
        /* auto textarea height */
        $('#contents').each(function () {
            // set init height
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        }).on('input', function () {
            // bind auto height
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });
    };

    /* 标签初始化 */
    mount();
    function mount() {
        $.ajax({
            type: "get",
            url: "/crudres/getLabel",
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                if (data.code === 200) {
                    labelList = data.result;
                    load(labelList);
                    //选中过的按钮变色
                    var labelIdBegin = new Array();
                    if(labelIds.length > 0){
                        labelIdBegin = "${resource.labelId}".split(',')
                        for (var i = 0; i < labelIdBegin.length; i++) {
                            $('#label' + labelIdBegin[i]).removeClass('re-btn-unselected');
                            /* check BOOK */
                            if (labelIdBegin[i] == ${bookLabelId}) {
                                $('#contents').removeClass('re-hide');
                                setTextareaHeight(); // must after remove re-hide
                            }
                        }
                    }
                } else
                    message(data.msg, false);
            }, error: function (err) {
                message("添加失败：" + err, false);
            }
        });
    }

    /* 标签载入实现 */
    function load(tagList) {
        var htmlStr = "";
        for (var j = 0; j < tagList.length; j++) {
            htmlStr += "<div class=\"col-md-12 row\">";
            for (var i = 0; i < tagList[j].length; i++) {
                switch (i) {
                    case 0: {
                        htmlStr += "<div>";
                        htmlStr += "<a class=\"re-btn re-label-header\" disabled=\"disabled\">" + tagList[j][i].name + "</a>";
                        htmlStr += "</div>";
                        htmlStr += "<div class=\"col-md-10\" style=\"line-height:45px;\">";
                        break;
                    }
                    default: {
                        var tagid = tagList[j][i].id;
                        // console.log("tagid!!"+tagid)
                        var tempGroup = "label" + tagid;
                        // console.log("tempGroup: "+tempGroup)
                        var uplevelid = tagList[j][i].uplevelid;
                        // console.log("uplevelid: "+uplevelid)
                        htmlStr += "<button id=\"" + tempGroup + "\" class=\"re-btn re-btn-unselected re-label-child\" onclick=\"labelButton(" + tagid + ")\">" + tagList[j][i].name + "</button>";
                        // htmlStr += "</span>";
                    }
                }
            }
            htmlStr += "</div>";
            htmlStr += " <br/>";
            htmlStr += "</div>";
        }
        // console.log(htmlStr);
        $("#labels").html(htmlStr);
    }

    /* 标签按钮切换 */
    function labelButton(id) {
        if ($('#label' + id).hasClass('re-btn-unselected')) {
            $('#label' + id).removeClass('re-btn-unselected');
            labelIds = labelIds + ',' + id;
            console.log("labelIds" + labelIds);
            /* check BOOK */
            if (id == ${bookLabelId}) { $('#contents').removeClass('re-hide'); }
        } else {
            $('#label' + id).addClass('re-btn-unselected');
            labelIds = labelIds.replace(',' + id, '');
            console.log("labelIds" + labelIds);
            /* check BOOK */
            if (id == ${bookLabelId}) { $('#contents').addClass('re-hide'); }
        }
    }

    /* 群组按钮切换 */
    function groupButton(id) {
        if ($('#group' + id).hasClass('re-btn-unselected')) {
            $('#group' + id).removeClass('re-btn-unselected');
            groupIds = groupIds + ',' + id;
            console.log("groupIds" + groupIds);
        } else {
            $('#group' + id).addClass('re-btn-unselected');
            groupIds = groupIds.replace(',' + id, '');
            console.log("groupIds" + groupIds);
        }
    }

    /* 模板功能 */
    var templateId = -1;
    function templateButton(id) {
        if (templateId != id) {
            // use template
            // check
            $.tipModal('confirm', 'warning', '确定应用模板？<br>（注意: 输入框当前内容将被覆盖! ）', function (result) {
                if (result == true) {
                    // do
                    $.ajax({
                        type: "get",
                        url: "../crudres/getTemplateCode?id=" + id,
                        success: function (data) {
                            tinyMCE.activeEditor.setContent(data["templateCode"]);
                            $('#template' + id).removeClass('re-btn-unselected');
                            if(templateId != -1){
                                $('#template' + id).addClass('re-btn-unselected');
                            }
                            templateId = id;
                            console.log("templateId " + templateId);
                            $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '应用模板成功！'});
                        },
                        error: function () {
                            $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '应用模板失败！'});
                        }
                    })
                }
            });
        } else {
            // cancel template
            // check
            $.tipModal('confirm', 'warning', '确定取消模板？<br>（注意: 输入框当前内容将被清空! ）', function (result) {
                if (result == true) {
                    // do
                    tinyMCE.activeEditor.setContent("");
                    $('#template' + id).addClass('re-btn-unselected');
                    templateId = -1;
                    console.log("templateId " + templateId);
                }
            });
        }
    }

    /* 群组初始化 */
    $(document).ready(function () {
        var groupIdBegin = new Array();
        if(groupIds.length > 0){
            groupIdBegin = "${resource.groupId}".split(',')
            for (var i = 0; i < groupIdBegin.length; i++) {
                // console.log(groupIdBegin[i])
                $('#group' + groupIdBegin[i]).removeClass('re-btn-unselected');
            }
        }
    })

    /* 提交保存资源 */
    function submit() {
        var title = $("#title").val();
        // var group = $("#group").val();
        var id = ${resource.id};
        var text = tinyMCE.activeEditor.getContent();
        var group = groupIds.substring(1);
        var label = labelIds.substring(1);
        var atta = JSON.stringify(attachmentNew);
        var superior = 0;
        var contents = $('#contents').val();

        if (title == "") {
            $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '资源标题不可为空'});
            return false;
        } else if (text == "") {
            $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '资源正文不可为空'});
            return false;
        } else {
            loading("show");
            <%--//处理\n换行符--%>
            text = text.replaceAll("\n", "");
            $.post("../crudres/editdata", {
                id: id,
                title: title,
                group: group,
                label: label,
                text: text,
                attachment: atta,
                superior: superior,
                contents: contents
            }, function (data) {
                if (data.msg == 'SUCCESS') {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '编辑资源成功'});
                    loading("reset");
                    window.location.href = "<%=request.getContextPath()%>/resource/resource?id=${resource.id}";
                } else if (data.msg == '必填项未填写完整') {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '必填项必须填写完成'});
                    loading("reset");
                } else {
                    $.fillTipBox({type: 'error', icon: 'glyphicon-alert', content: '编辑资源失败'});
                    // alert("保存失败0.0");
                    loading("reset");
                }
            });
        }
    }
</script>
<!-- END: Scripts -->
</html>